package com.jieshuibao.controller.wx;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.controller.GenericController;
import com.jieshuibao.model.db.Card;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.db.WxUser;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.LoginRequest;
import com.jieshuibao.service.CardService;
import com.jieshuibao.service.ChangeCodeService;
import com.jieshuibao.service.CoreService;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.service.WxUserService;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.util.WithdrawUtil;
import com.jieshuibao.wx.po.WxEnterpriseReq;
import com.jieshuibao.wx.util.PayCommonUtil;

/**
 * @author :liuxb@jieshuibao.com
 * @version ：2018年9月6日 上午10:53:59
 * 类说明
 */
@Controller
@RequestMapping("/wx")
public class WxUserController extends GenericController{
	
	@Resource
	private UserService UserService;
	
	@Resource
	private WxUserService WxUserService;
	
	@Resource
	private ChangeCodeService changeCodeService;
	
	@Resource
	private RedisService redisService;
	
	@Resource
	private CardService cardService;
	
	@Autowired
	protected CoreService coreService;
	
	@RequestMapping(value = "/account", method = RequestMethod.POST)
	@ResponseBody
	public Object wxRegist(HttpServletRequest request,@RequestBody LoginRequest loginRequest) {
		BaseRes<String> res = new BaseRes<String>();
		
		try {
			String cookieId = request.getHeader("cookieId");
			logger.info("接收：" + mapper.writeValueAsString(loginRequest+cookieId));
			String phoneNumber = loginRequest.getPhoneNumber();
			String code = loginRequest.getCode();
			String smsMessageSid = loginRequest.getSmsMessageSid();
			
			if (StringUtils.isBlank(phoneNumber)||StringUtils.isBlank(code)||StringUtils.isBlank(smsMessageSid)||StringUtils.isBlank(cookieId)) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			
			if (!StringUtils.isMobile(phoneNumber)) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			Map<String, String> checkSms = changeCodeService.checkSmsApp(smsMessageSid, code,phoneNumber);
			String codeValue = checkSms.get("code");
			if (!codeValue.equals("1")) {
				return checkSms;
			}
			WxUser wxUser = WxUserService.getWxUserByOpenid(cookieId);
			if (wxUser==null) {
				WxMpUser wxMpUser = coreService.getUserInfo(cookieId, "zh_CN");
				if (wxMpUser!=null) {
					String openId = wxMpUser.getOpenId();
					String city = wxMpUser.getCity();
					String country = wxMpUser.getCountry();
					String headImgUrl = wxMpUser.getHeadImgUrl();
					String nickname = wxMpUser.getNickname();
					String province = wxMpUser.getProvince();
					String sex = wxMpUser.getSex();
					String unionId = wxMpUser.getUnionId();
					WxUser user = new WxUser();
					user.setOpenid(openId);
					user.setCity(city);
					user.setCountry(country);
					user.setHeadimgurl(headImgUrl);
					user.setNickname(nickname);
					user.setProvince(province);
					user.setSex(sex);
					user.setUnionid(unionId);
					user.setCreateTime(new Date());
					// 以前关注过
					WxUserService.addWxUser(user);
					return  WxUserService.bingdingWxuser(phoneNumber, cookieId);
				}else {
					
					res.setCode(BaseRes.ERRORPARAM_CODE);
					res.setDes("openId错误");
					return res;
				}
			}
			String userId2 = wxUser.getUserId();
			if (StringUtils.isBlank(userId2)) {
				return  WxUserService.bingdingWxuser(phoneNumber, cookieId);
				
			}else {
				//
				User user = UserService.getUserByPhoneNumber(userId2);
				if (user==null) {
					//未绑定
					return  WxUserService.bingdingWxuser(phoneNumber, cookieId);
				}else {
					//已经绑定
					res.setCode(BaseRes.FAIL_CODE);
					res.setDes("已经注册过！");
					return res;
				}
				
			}
			
	
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);//
			res.setDes(BaseRes.FAIL_DES);
		}
		return res;
	}
	
	@RequestMapping(value = "/binding/card", method = RequestMethod.POST)
	@ResponseBody
	public Object wxQaCardBinDing(HttpServletRequest request,@RequestBody(required=false) Card req) {
		BaseRes<String> res = new BaseRes<String>();
		
		try {
			logger.info("接收：" + mapper.writeValueAsString(req));
			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
			String phoneNumber = cookieUser.getPhoneNumber();
			if(req==null){
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			Long id = req.getId();
			String securityCode = req.getSecurityCode();
			String string = redisService.get("wx_"+phoneNumber+"_BINDING");
			if (StringUtils.isBlank(string)) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes("已经超时！");
				return res;
			}
			if (StringUtils.isBlank(phoneNumber)||StringUtils.isBlank(securityCode)) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			if (id==null||id<=0) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			User user =UserService.getUserByPhoneNumber(phoneNumber);
			if (user!=null) {
				Long userSrc = user.getUserSrc();
				if(userSrc!=null&&userSrc>0){
					res.setCode(BaseRes.FAIL_CODE);
					res.setDes("已绑定渠道");
					return res;
				}
				return cardService.bindingQACard(null, phoneNumber, req);
			}
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);//
			res.setDes(BaseRes.FAIL_DES);
		}
		return res;
	}

	//公众号提现
	@RequestMapping(value="/wp/withdraw",method=RequestMethod.POST)
	@ResponseBody
	public Object wpWithDraw(@RequestBody WxEnterpriseReq req,HttpServletRequest request){
		BaseRes<String> res = new BaseRes<String>();
		
		try {
			String cookieId = request.getHeader("cookieId");
			logger.info("接收：" + mapper.writeValueAsString(req+cookieId));
			
			if (StringUtils.isBlank(cookieId)) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes("cooieid错误！"+cookieId);
				return res;
			}
			double money = req.getMoney();
			
			if(!WithdrawUtil.isAgree(money)){
				res.setCode(PayCommonUtil.FAIL_CODE);
				res.setDes("最低提现金额为20元哦！");
				return res;
			}
			
			WxUser wxUser = WxUserService.getWxUserByOpenid(cookieId);
			if (wxUser==null) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
			if (cookieUser==null) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes("数据异常！");
				return res;
			}
			String userName = cookieUser.getUserName();
			if (StringUtils.isBlank(userName)) {
				res.setCode(BaseRes.FAIL_CODE);
				res.setDes("请完善资料的真实姓名！");
				return res;
			}
			
			 return WxUserService.wxUserWithdraw(cookieUser, money, cookieId, request);
			
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes(BaseRes.FAIL_DES);
			return res;
		}
	}
}
